package com.googlecode.microanalyst.palette.edit;

import java.beans.PropertyChangeEvent;

import org.eclipse.draw2d.IFigure;
import org.eclipse.gef.AccessibleEditPart;
import org.eclipse.gef.EditPolicy;
import org.eclipse.gef.Request;
import org.eclipse.gef.RequestConstants;
import org.eclipse.swt.accessibility.AccessibleControlEvent;
import org.eclipse.swt.accessibility.AccessibleEvent;

import com.googlecode.microanalyst.designer.edit.AnalysisEditPart;
import com.googlecode.microanalyst.palette.figure.OutputFigure;
import com.googlecode.microanalyst.palette.i18n.PaletteMessages;
import com.googlecode.microanalyst.palette.model.Output;
import com.googlecode.microanalyst.palette.model.OutputProperties;

public class OutputEditor extends AnalysisEditPart {

	public OutputEditor() {
	}

	@Override
	protected AccessibleEditPart createAccessible() {
		return new AccessibleGraphicalEditPart() {
			public void getValue(AccessibleControlEvent e) {
				final Output model = getOutput();
				e.result = model.getFilename();
			}

			public void getName(AccessibleEvent e) {
				e.result = PaletteMessages.Palette_Tool_Output;
			}
		};
	}

	protected Output getOutput() {
		return (Output) getModel();
	}

	@Override
	protected IFigure createFigure() {
		OutputFigure figure = new OutputFigure();
		return figure;
	}

	protected void createEditPolicies() {
		super.createEditPolicies();
		//installEditPolicy(EditPolicy.GRAPHICAL_NODE_ROLE, null);
		installEditPolicy(EditPolicy.DIRECT_EDIT_ROLE,
				new OutputDirectEditPolicy());
		installEditPolicy(EditPolicy.COMPONENT_ROLE, new OutputEditPolicy());
	}

	private void performDirectEdit() {
		OutputFigure f = (OutputFigure) getFigure();
		OutputCellEditorLocator cel = new OutputCellEditorLocator(f);
		OutputEditManager em = new OutputEditManager(this, cel);
		em.show();
	}

	public void performRequest(Request request) {
		if (request.getType() == RequestConstants.REQ_DIRECT_EDIT)
			performDirectEdit();
	}

	public void propertyChange(PropertyChangeEvent evt) {
		if (evt.getPropertyName().equalsIgnoreCase(OutputProperties.PROPERTY_FILENAME))
			refreshVisuals();
		else
			super.propertyChange(evt);
	}

	protected void refreshVisuals() {
		final String filename = getOutput().getFilename();
		final String defaultName = "<<" + PaletteMessages.Palette_Tool_Output + ">>";
		//show the default name if noo filename is given
		final String text = filename == null || "".equals(filename) ? defaultName : filename;
		final OutputFigure fig = (OutputFigure) getFigure();
		fig.setText(text);
		super.refreshVisuals();
	}

}
